package wox.lonice.btctrade.service.Impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import wox.lonice.btctrade.common.BaseConstant;
import wox.lonice.btctrade.dto.LinkeEntityDto;
import wox.lonice.btctrade.service.ConsumeService;
import wox.lonice.utis.MailUtil;
import wox.lonice.utis.ObjectUtil;

import java.util.concurrent.*;

/**
 * <p>描述：接口实现</p>
 *
 * @author LoNice
 * @Date 2018/5/29 9:36
 */
@Service
public class ConsumeServiceImpl implements ConsumeService, BaseConstant {
    private Logger logger = LoggerFactory.getLogger(ConsumeService.class);

    @Override
    public void dealLinkeDto() {
        ExecutorService pool = Executors.newFixedThreadPool(threadPoolNum);
        final StringBuffer rsultMaileBody = new StringBuffer();
        //不是空值，将从线程安全的队列中取出一个数据，取出->移除
        while(ObjectUtil.isNotEmpty(LINKED_BLOCKING_DEQUE) && !LINKED_BLOCKING_DEQUE.isEmpty()){
            final LinkeEntityDto linkeEntityDto = LINKED_BLOCKING_DEQUE.poll();
            Future<String> future = pool.submit((Callable<String>) () ->{
                System.out.println("取出数据: " + linkeEntityDto);
                //设置唯一key
                String key = linkeEntityDto.getArea() + ":" + linkeEntityDto.getCoin();
                //当前mailMap存在该key
                if(mailMap.containsKey(key)){
                    Long thisTime = mailMap.get(key);
                    //小于5分钟，不发送邮件
                    if(thisTime - linkeEntityDto.getThisDate() < 300000){
                        return null;
                    }
                }
                //记录key，并发送邮件
                mailMap.put(key, linkeEntityDto.getThisDate());
                //发送邮件
//                MailUtil.sendMail("451932185@qq.com", linkeEntityDto.getDomain() + " : 行情波动信息", linkeEntityDto.getBody());
                return linkeEntityDto.getBody();
            });
            try {
                String appedStr = future.get();
                if(ObjectUtil.isNotEmpty(appedStr)){
                    rsultMaileBody.append(appedStr);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        if(ObjectUtil.isNotEmpty(rsultMaileBody.toString()) && !"".equals(rsultMaileBody.toString())){
            MailUtil.sendMail("451932185@qq.com", "行情波动信息", rsultMaileBody.toString());
        }
        pool.shutdown();
    }
}
